/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.haipv.gtkhoa501.controller;

import com.haipv.gtkhoa501.Midlet;
import com.haipv.gtkhoa501.model.Signs;
import com.haipv.gtkhoa501.model.Var;
import com.haipv.gtkhoa501.screen.AboutScreen;
import com.haipv.gtkhoa501.screen.DetailSignScreen;
import com.haipv.gtkhoa501.screen.ExamReviewScreen;
import com.haipv.gtkhoa501.screen.ExamScreen;
import com.haipv.gtkhoa501.screen.HelpScreen;
import com.haipv.gtkhoa501.screen.ListSignsScreen;
import com.haipv.gtkhoa501.screen.MainScreen;
import com.haipv.gtkhoa501.screen.MainSignsScreen;
import com.haipv.gtkhoa501.screen.ReviewScreen;
import com.haipv.gtkhoa501.screen.SearchReviewScreen;
import com.nokia.lwuit.components.HeaderBar;
import com.nokia.mid.ui.CategoryBar;
import com.nokia.mid.ui.ElementListener;
import com.nokia.mid.ui.IconCommand;
import com.sun.lwuit.Button;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Label;
import com.sun.lwuit.TextArea;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;
import java.security.DigestException;
import java.util.Vector;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;

/**
 *
 * @author PHANHAI
 */
public class Controller implements CommandListener, ActionListener {

    private static Controller instance = null;
    public static CategoryBar categoryBarReview, categoryBarExam, categoryBarExamReview;
    private static Resources theme;
    private StorageData storage;
    private TimerManager timer;
    //private ExamScreen examScreen = null;
    public static Midlet main;
    private MainScreen mainSecreen2;

    private Controller() {
        loadTheme();
        storage = StorageData.getInstance();
        timer = TimerManager.getInstance();
        setCategorie();
    }

    public static Controller getInstance() {
        if (instance == null) {
            instance = new Controller();
        }
        return instance;
    }

    public void setCategorie() {
        IconCommand[] iconCommands = new IconCommand[2];
        IconCommand[] iconCommands1 = new IconCommand[3];
        Image icon = null;

        for (int i = 0; i < iconCommands1.length; i++) {
            try {
                icon = Image.createImage("/images/categoriBar/icon" + (i + 1) + ".png");

            } catch (Exception ex) {
                ex.printStackTrace();
            }
            if (i == 0) {
                iconCommands[i] = new IconCommand("", icon, null, Command.SCREEN, 1);
            }
            if (i == 2) {
                iconCommands[i - 1] = new IconCommand("", icon, null, Command.SCREEN, 1);
            }
            iconCommands1[i] = new IconCommand("", icon, null, Command.SCREEN, 1);

        }
        categoryBarReview = new CategoryBar(iconCommands, true, CategoryBar.ELEMENT_MODE_RELEASE_SELECTED);
        categoryBarReview.setElementListener(new CategoryElementListener());


        categoryBarExam = new CategoryBar(iconCommands1, true, CategoryBar.ELEMENT_MODE_RELEASE_SELECTED);
        categoryBarExam.setElementListener(new CategoryElementListener());

        categoryBarExamReview = new CategoryBar(iconCommands, true, CategoryBar.ELEMENT_MODE_RELEASE_SELECTED);
        categoryBarExamReview.setElementListener(new CategoryElementListener());

    }

    /**
     * Xử lý sự kiện.
     *
     * @param eventType sự kiện cần xử lý Event
     * @param evt Dữ liệu cần xử lý
     */
    public void handleEvent(int eventType, Event evt) {
        switch (eventType) {
            case Event.MAIN_ACTION:
                showMain();
                break;
            case Event.ABOUT_ACTION:
                showAbout();
                break;
            case Event.HELP_ACTION:
                showHelp();
                break;
            case Event.SIGN_VIEW:
                showSIGN();
                break;
            case Event.SIGN_SELECT:
                showSignSelect(evt);
                break;
            case Event.SIGN_DETAIL:
                showSignDetail(evt);
                break;
            case Event.REVIEW_SEEK:
                showReview(evt);
                break;
            case Event.REVIEW_SEARCH:
                showReviewSearch();
                break;
            case Event.REVIEW_NEXT:
                showNextReview();
                break;
            case Event.REVIEW_PREV:
                showPreReview();
                break;
            case Event.EXAM_ACTION:
                showSelectExam(evt);
                break;
            case Event.EXAM_VIEW:
                showExam(evt);
                break;
            case Event.EXAM_NEXT:
                showExamNext();
                break;
            case Event.EXAM_PREV:
                showExamPrev();
                break;
            case Event.EXAM_CONFIRM:
                showConfirm();
                break;
            case Event.EXAM_FINISH:
                showResult();
                break;
            case Event.EXAM_REVIEW:
                showExamReview(evt);
                break;
            case Event.EXAM_REVIEW_NEXT:
                showExamReviewNext();
                break;
            case Event.EXAM_REVIEW_PREV:
                showExamReviewPrev();
                break;
        }
    }

    private void showMain() {
        if (categoryBarReview.getVisibility() == true) {
            categoryBarReview.setVisibility(false);
        }
        if (categoryBarExam.getVisibility() == true) {
            categoryBarExam.setVisibility(false);
        }
        if (categoryBarExamReview.getVisibility() == true) {
            categoryBarExamReview.setVisibility(false);
        }
        if (mainSecreen2 == null) {
            mainSecreen2 = new MainScreen();
        }
        mainSecreen2.show();

//        Runtime.getRuntime().gc();
    }

    private void showAbout() {
        AboutScreen aboutScreen = new AboutScreen();
        aboutScreen.show();
        Runtime.getRuntime().gc();
    }

    private void showHelp() {
        HelpScreen helpScreen = new HelpScreen();
        helpScreen.show();
        Runtime.getRuntime().gc();
    }

    private void showSIGN() {
        MainSignsScreen mainSignsScreen = new MainSignsScreen();
        mainSignsScreen.showForm();
        Runtime.getRuntime().gc();
    }

    private void showSignSelect(Event evt) {
        //System.out.println("ID:"+Integer.parseInt(evt.getValue("TYPE").toString()));


        int type = Integer.parseInt(evt.getValue("TYPE").toString());
        String title = getType(type);//evt.getValue("NAME").toString();

        Vector signs = storage.getSigns(type);

        ListSignsScreen listSignScreen = new ListSignsScreen(title, signs);
        listSignScreen.showForm();
        Runtime.getRuntime().gc();
    }

    private void showSignDetail(Event evt) {
        int id = Integer.parseInt(evt.getValue("ID").toString());
        Signs sign = storage.getSign(id);
        DetailSignScreen detai = new DetailSignScreen();
        detai.show(sign);
    }

    private String getType(int type) {
        return (Var.bienBao[type - 1]);

    }

    private void showReview(Event evt) {
        ReviewScreen reviewScreen = new ReviewScreen(Integer.parseInt(evt.getValue("INDEX").toString()));
        reviewScreen.showForm();
    }

    private void showExamReview(Event evt) {
        ExamReviewScreen reviewScreen = new ExamReviewScreen(Integer.parseInt(evt.getValue("INDEX").toString()));
        reviewScreen.showForm();
    }

    private void showExamReviewNext() {
        if (Var.indexExam == 30) {
            Var.indexExam = 0;
        }
        Var.indexExam++;
        Event evt = new Event();
        evt.setKey("INDEX", Var.indexExam + "");
        handleEvent(Event.EXAM_REVIEW, evt);
    }

    private void showExamReviewPrev() {
        if (Var.indexExam == 1) {
            Var.indexExam = 31;
        }
        Var.indexExam--;
        Event evt = new Event();
        evt.setKey("INDEX", Var.indexExam + "");
        handleEvent(Event.EXAM_REVIEW, evt);
    }

    private void showReviewSearch() {
        SearchReviewScreen searchReviewScreen = new SearchReviewScreen();
        searchReviewScreen.showForm();
    }

    private void showNextReview() {
        if (Var.indexReview == storage.NUM_CAUHOI) {
            Var.indexReview = 0;
        }
        Var.indexReview++;
        Event evt = new Event();
        evt.setKey("INDEX", Var.indexReview + "");
        handleEvent(Event.REVIEW_SEEK, evt);
    }

    private void showPreReview() {
        if (Var.indexReview == 1) {
            Var.indexReview = storage.NUM_CAUHOI + 1;
        }
        Var.indexReview--;
        Event evt = new Event();
        evt.setKey("INDEX", Var.indexReview + "");
        handleEvent(Event.REVIEW_SEEK, evt);
    }

    private void showExam(Event evt) {
        ExamScreen examScreen = new ExamScreen(Integer.parseInt(evt.getValue("INDEX").toString()));
        examScreen.showForm();

//        SetFullScreen();
    }

    private void showExamNext() {
        if (Var.indexExam == 30) {
            Var.indexExam = 0;
        }
        Var.indexExam++;
        Event evt = new Event();
        evt.setKey("INDEX", Var.indexExam + "");
        handleEvent(Event.EXAM_VIEW, evt);
    }

    private void showExamPrev() {
        if (Var.indexExam == 1) {
            Var.indexExam = 31;
        }
        Var.indexExam--;
        Event evt = new Event();
        evt.setKey("INDEX", Var.indexExam + "");
        handleEvent(Event.EXAM_VIEW, evt);
        SetFullScreen();
    }
    Command ok, ok1, canl1;
    Command canl;

    private void showConfirm() {
        //kết thúc bài thi
        Alert alert = new Alert("thông báo", "bạn có chắc muốn kết thúc bài thi", null, AlertType.CONFIRMATION);
        ok = new Command("ĐỒNG Ý", Command.ITEM, 1);
        canl = new Command("BỎ QUA", Command.ITEM, 0);
        alert.addCommand(ok);
        alert.addCommand(canl);
        alert.setCommandListener(this);

        Display.getDisplay(main).setCurrent(alert);
        /*
        //        categoryBarExam.setVisibility(false);
        Dialog diag = new Dialog("thông báo");
        //diag.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
        diag.addComponent(new TextArea("bạn có chắc muốn kết thúc bài thi", 2, 10));
        ketThuc = new com.sun.lwuit.Command("ĐỒNG Ý");
        tiepTuc = new com.sun.lwuit.Command("BỎ QUA");
        diag.addCommand(ketThuc);
        diag.addCommand(tiepTuc);
        //        ketThuc.addActionListener(this);
        //        tiepTuc.addActionListener(this);
        diag.addCommandListener(new ActionListener() {
        
        public void actionPerformed(ActionEvent ae) {
        if (ae.getCommand() == ketThuc) {
        System.out.println("chay...");
        handleEvent(Event.EXAM_FINISH, null);
        } else if (ae.getCommand() == tiepTuc) {
        System.out.println("2chay...");
        Event evt = new Event();
        evt.setKey("INDEX", Var.indexExam + "");
        handleEvent(Event.EXAM_VIEW, evt);
        }
        }
        });
        diag.showDialog();
        //SetFullScreen();
         * */
    }
    com.sun.lwuit.Command B1, B2, CDEF, BACK, dongY, boQua, ketThuc, tiepTuc;
    Button b1, b2, cdef;

    private void showSelectExam2(final Event evt) {
        Dialog diag = new Dialog("thông báo");
        diag.addComponent(new Label("mời bạn chọn hạng lái xe"));
        B1 = new com.sun.lwuit.Command("B1");
        CDEF = new com.sun.lwuit.Command("CDEF");
        B2 = new com.sun.lwuit.Command("B2");
        BACK = new com.sun.lwuit.Command("back");
        diag.setBackCommand(BACK);
        diag.addCommand(B1);
        diag.addCommand(B2);
        diag.addCommand(CDEF);
        diag.addCommand(BACK);
        diag.addCommandListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                int type = 1;
                if (ae.getCommand() == B1) {
                    type = 1;
                } else if (ae.getCommand() == B2) {
                    type = 2;
                } else if (ae.getCommand() == CDEF) {
                    type = 3;
                } else if (ae.getCommand() == BACK) {
                    handleEvent(Event.MAIN_ACTION, null);
                }

                if (ae.getCommand() == B1 || ae.getCommand() == B2 || ae.getCommand() == CDEF) {
                    timer.start(1200);
                    storage.loadExams(type);
                    showExam(evt);
                }
            }
        });
        diag.showDialog();
        Runtime.getRuntime().gc();
    }
    com.sun.lwuit.Command troVe;

    private void showSelectExam(final Event evt) {
//        Alert alert = new Alert("thông báo", "mời bạn chọn hạng lái xe", null, AlertType.CONFIRMATION);
        com.sun.lwuit.Form form = new com.sun.lwuit.Form("Chọn hạng lái xe");

        b1 = new Button("B1");
        b2 = new Button("B2");
        cdef = new Button("CDEF");
        troVe = new com.sun.lwuit.Command("trở về");
        form.setBackCommand(troVe);

        HeaderBar header = new HeaderBar("Chọn hạng lái xe");
        header.setHeaderTitleColor(Var.colorHearder);
        header.getStyle().setBgColor(Var.colorWhite);
        form.addComponent(header);
        form.addComponent(b1);
        form.addComponent(b2);
        form.addComponent(cdef);
        b1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                timer.start(1200);
                storage.loadExams(1);
                showExam(evt);
            }
        });
        b2.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                timer.start(1200);
                storage.loadExams(2);
                showExam(evt);
            }
        });
        cdef.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                timer.start(1200);
                storage.loadExams(3);
                showExam(evt);
            }
        });
        form.addCommand(troVe);
        form.addCommandListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                if (ae.getCommand() == troVe) {
                    handleEvent(Event.MAIN_ACTION, null);
                }
            }
        });
        form.show();
        SetFullScreen();
    }

    private void showResult2() {
        System.out.println("dcm");
        Dialog diag2 = new Dialog("kết quả thi");
        int diem=storage.getResult();
        String ketQua=" đỗ. ";
        if (diem < 25)  ketQua=" trượt. ";
        diag2.addComponent(new TextArea("trả lời đúng " + diem + "/" + storage.NUM_EXAM + ".\n Kết quả:"+ketQua+"\n Bạn có muốn xem lại bài thi không?", 4, 10));
        dongY = new com.sun.lwuit.Command("ĐỒNG Ý");
        boQua = new com.sun.lwuit.Command("BỎ QUA");
        diag2.addCommand(dongY);
        diag2.addCommand(boQua);
        diag2.addCommandListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                if (ae.getCommand() == dongY) {
                    //  xử lý tại đây  
                    Var.indexExam = 1;
                    Event evt = new Event();
                    evt.setKey("INDEX", Var.indexExam + "");
                    handleEvent(Event.EXAM_REVIEW, evt);
                } else if (ae.getCommand() == boQua) {
                    handleEvent(Event.MAIN_ACTION, null);
                }
            }
        });
        diag2.showDialog();
    }

    private void showResult() {
        int diem=storage.getResult();
        String ketQua=" đỗ. ";
        if (diem < 25)  ketQua=" trượt. ";
        Alert alert1 = new Alert("kết quả thi", " Trả lời đúng " + diem + "/" + storage.NUM_EXAM + ".\n Kết quả:"+ketQua+"\n Bạn có muốn xem lại bài thi không?", null, AlertType.CONFIRMATION);
        ok1 = new Command("ĐỒNG Ý", Command.ITEM, 1);
        canl1 = new Command("BỎ QUA", Command.ITEM, 0);
        alert1.addCommand(ok1);
        alert1.addCommand(canl1);
        alert1.setCommandListener(this);
        Display.getDisplay(main).setCurrent(alert1);
        SetFullScreen();
    }

    public void showMessenger(String title, String messenger) {
        Alert ale = new Alert(title, messenger, null, AlertType.INFO);
        Display.getDisplay(main).setCurrent(ale);

        //Dialog.show(title, messenger, "ĐÓNG", null);
        SetFullScreen();
    }

    public void SetFullScreen() {
        com.sun.lwuit.Display.getInstance().setForceFullScreen(true);
        com.sun.lwuit.Display.setObjectTrait(com.sun.lwuit.Display.getInstance().getImplementation(), "nokia.ui.canvas.status_zone", Boolean.TRUE);
    }

    public void setMain(Midlet aThis) {
        this.main = aThis;
    }

    public void commandAction(Command c, Displayable d) {
        if (c == ok) {
            //splashCanvas = SplashCanvas.getInstance();
            System.out.println("chay dong y");
            Form a = new Form(null);
            javax.microedition.lcdui.Display.getDisplay(main).setCurrent(a);
            //  xử lý tại đây  
            handleEvent(Event.EXAM_FINISH, null);
        } else if (c == canl) {

            Event evt = new Event();
            evt.setKey("INDEX", Var.indexExam + "");
            handleEvent(Event.EXAM_VIEW, evt);
        } else if (c == ok1) {
            //  xử lý tại đây  
            Var.indexExam = 1;
            Event evt = new Event();
            evt.setKey("INDEX", Var.indexExam + "");
            handleEvent(Event.EXAM_REVIEW, evt);
        } else if (c == canl1) {
            handleEvent(Event.MAIN_ACTION, null);
        }
    }

    public static void loadTheme() {
        try {
            if (theme == null) {
                theme = Resources.open("/asha2013_theme.res");
            }
            UIManager.getInstance().setThemeProps(theme.getTheme(theme.getThemeResourceNames()[0]));
        } catch (Throwable ex) {
        }
    }

    public void actionPerformed(ActionEvent ae) {
        /*int type = 1;
        if (ae.getSource() == b1) {
        type = 1;
        } else if (ae.getSource() == b2) {
        type = 2;
        } else if (ae.getSource() == cdef) {
        type = 3;
        }
        
        if (ae.getSource() == b1 || ae.getSource() == b2 || ae.getSource() == cdef) {
        timer.start(1200);
        storage.loadExams(type);
        showExam(evt);
        }
         */
    }

    class CategoryElementListener implements ElementListener {

        public void notifyElementSelected(CategoryBar bar, int selectedIndex) {
            if (bar == categoryBarExam) {
                if (selectedIndex == 0) {
                    handleEvent(Event.EXAM_PREV, null);
                } else if (selectedIndex == 1) {
                    // bắt sự kiện nhấn tích tại thanh categori
                    handleEvent(Event.EXAM_CONFIRM, null);

                } else if (selectedIndex == 2) {
                    handleEvent(Event.EXAM_NEXT, null);
                }
            } else {
                if (bar == categoryBarReview) {
                    if (selectedIndex == 0) {
                        handleEvent(Event.REVIEW_PREV, null);
                    } else if (selectedIndex == 1) {
                        handleEvent(Event.REVIEW_NEXT, null);
                    }
                } else if (bar == categoryBarExamReview) {
                    if (selectedIndex == 0) {
                        handleEvent(Event.EXAM_REVIEW_PREV, null);
                    } else if (selectedIndex == 1) {
                        handleEvent(Event.EXAM_REVIEW_NEXT, null);
                    }
                }
            }
        }
    }
}